﻿
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;


namespace WebApiDemo
{
    public class ApiResultFilterAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 进入action之前做权限验证
        /// </summary>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var token = false;
            //权限验证省略
            if (token)
            {
                ResponseApi<object> result = new ResponseApi<object>();
                // 取得由 API 返回的状态代码
                result.code = (int)HttpStatusCode.Unauthorized;
                // 取得由 API 返回的资料
                result.data = null;
                result.msg = "invalid ticket value";

                HttpResponseMessage response = new HttpResponseMessage
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result),
                       Encoding.GetEncoding("UTF-8"), "application/json")
                };
                //结果转为自定义消息格式
                HttpResponseMessage httpResponseMessage = response;

                // 重新封装回传格式
                actionContext.Response = httpResponseMessage;
            }
        }
        /// <summary>
        /// 统一响应格式
        /// </summary>
        public override void OnActionExecuted(HttpActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            if (filterContext.ActionContext.Response != null)
            {
                ResponseApi<object> result = new ResponseApi<object>();
                // 取得由 API 返回的状态代码
                result.code = (int)filterContext.ActionContext.Response.StatusCode;
                // 取得由 API 返回的资料
                result.data = filterContext.ActionContext.Response.Content.ReadAsAsync<object>().Result;
                HttpResponseMessage response = new HttpResponseMessage
                {
                    Content = new StringContent(JsonConvert.SerializeObject(result),
                       Encoding.GetEncoding("UTF-8"), "application/json")
                };
                //结果转为自定义消息格式
                HttpResponseMessage httpResponseMessage = response;

                // 重新封装回传格式
                filterContext.Response = httpResponseMessage;

            }
        }
    }

}
